﻿using System;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.ValidationService;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.BizFacade.Services;

namespace Fuse8.ContentManagementFramework.BizFacade.Validation
{
    public class CmsPageValidationService : BaseEntityValidationService<CmsPage>
    {
        private readonly CmsPageService _service = new CmsPageService();

        internal CmsPageValidationService(CmsPageService service)
        {
            _service = service;
        }

        public CmsPageValidationService()
        {
        }

        public override ValidationResult Validate(CmsPage entityObject, ValidationActionType actionType)
        {
            Guard.ArgumentNotNull(entityObject, "entityObject");

            ValidationResult result = null;

            if (NeedValidateActionType(actionType) && entityObject.IsUrlRequired)
            {
                if (string.IsNullOrWhiteSpace(entityObject.PageUrl))
                {
                    result = new ValidationResult
                    {
                        IsValid = false,
                        ValidationMessage = "Page can't have empty url"
                    };
                }
                else
                {
                    var data = _service.GetPageByUrl(entityObject.PageUrl);

                    if ((data != null) && !(data.PublicPageId.Equals(entityObject.PublicPageId) || (data.Id.Equals(entityObject.Id))))
                    {
                        result = new ValidationResult
                        {
                            IsValid = false,
                            ValidationMessage = string.Format("Page with the specified url already exists: '{0}'", entityObject.PageUrl)
                        };
                    }
                }
            }

            return result ?? base.Validate(entityObject, actionType);
        }

        private static bool NeedValidateActionType(ValidationActionType actionType)
        {
            return (actionType == ValidationActionType.Create) || (actionType == ValidationActionType.Update);
        }
    }
}
